package com.lg.mengbase.app;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.lg.baselibrary.activity.IActivity;
import com.lg.baselibrary.app.ExceptionCrashHandlerApp;
import com.lg.baselibrary.utils.DeviceInfoUtil;
import com.lg.baselibrary.utils.FileDownloader;
import com.lg.hotfix.HotFix;
import com.lg.mengbase.api.ApiClient;
import com.lg.mengbase.entity.FixInfo;
import com.lg.mengbase.entity.ResponseBase;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by LiGang on 2017/5/28.
 */

public class App extends ExceptionCrashHandlerApp{
    @Override
    public void onCreate() {
        super.onCreate();
        //动态加载hack
        HotFix.getInstance().init(this);
        HotFix.getInstance().injectHack("hack.dex");
        //执行热修复框架逻辑
        excuteHotfixLogic();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if(activity instanceof IActivity){
                    IActivity iActivity = (IActivity) activity;
                    activity.setContentView(iActivity.provideContentViewLayout());
                    iActivity.initView();
                    iActivity.initData();
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });

    }

    /**
     * 执行热修复框架逻辑
     */
    private void excuteHotfixLogic() {
        log("进入热修复框架逻辑");
        hotfix();
        checkServerExistsFixFile();
    }

    /**
     * 检测服务器是否有修复文件
     */
    private void checkServerExistsFixFile() {
        new Subscriber<String>(){

            @Override
            public void onSubscribe(Subscription s) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        };
        log("开始检测服务器是否有修复文件");
        Observable<ResponseBase<FixInfo>> observable = ApiClient.instance().checkFix(DeviceInfoUtil.getPhoneBrand(), DeviceInfoUtil.getPhoneModel(), DeviceInfoUtil.getDeviceId(this),
                DeviceInfoUtil.getBuildVersion(), DeviceInfoUtil.getVersionCode(this));
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBase<FixInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBase<FixInfo> value) {
                        log("收到服务器返回的信息");
                        final FixInfo fixInfo = value.getData();
                        if(fixInfo.isHas_fix()){
                            String fixFileUrl = fixInfo.getFix_file_url();
                            String fileName = fixFileUrl.substring(fixFileUrl.lastIndexOf("/")+1);
                            final String fixSavePath = getFilesDir().getAbsolutePath()+File.separator+"fix"+File.separator+fileName;
                            log("fix文件保存地址："+fixSavePath);
                            File fixFile = new File(fixSavePath);
                            if(fixFile.exists()){
                                log("修复包已存在，不需要下载");
                                return;
                            }
                            log("当前版本："+fixInfo.getApp_version_code()+" 需要修复，修复包地址："+ fixFileUrl);
                            log("开始下载修复包");
                            downloadFix(fixFileUrl,fixSavePath,fixInfo);

                        }else{
                            log("当前版本："+fixInfo.getApp_version_code()+" 不需要修复");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        log("onError:"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        log("onComplete");
                    }
                });
    }
    private void downloadFix(String fixFileUrl, final String fixSavePath, final FixInfo fixInfo){
        log("下载地址："+fixFileUrl);
        log("保存地址："+fixSavePath);
        new FileDownloader().download(fixFileUrl, fixSavePath, new FileDownloader.DownloadCallback() {
            @Override
            public void onSuccess(File file) {
                log("下载完成："+file.getAbsolutePath());
                SharedPreferences preferences = getSharedPreferences("fix",MODE_PRIVATE);
                preferences.edit().putString("fix_app_version",fixInfo.getApp_version_code())
                        .putString("fix_file_path",fixSavePath)
                        .commit();
                hotfix();
            }

            @Override
            public void onFailed() {
                log("下载失败");
            }

            @Override
            public void onLoading(long total, long current) {

            }
        });
    }
    private void hotfix() {
        log("进行热修复");
        String appVersionCode = DeviceInfoUtil.getVersionCode(this);
        log("appVersionCode："+appVersionCode);
        SharedPreferences preferences = getSharedPreferences("fix",MODE_PRIVATE);
        String fixAppVersion = preferences.getString("fix_app_version", "");
        log("fixAppVersion："+fixAppVersion);
        String fixFilePath = preferences.getString("fix_file_path", "");
        log("fixFilePath:"+fixFilePath);
        File fixFile = new File(fixFilePath);
        if(appVersionCode.equals(fixAppVersion)){
            log("appVersionCode与fixAppVersion一致");
            if(fixFile.exists()){
                log("fixFile存在，开始进行修复");
                HotFix.getInstance().init(this);
                HotFix.getInstance().inject(fixFilePath);
                log("修复完成");
            }
        }else{
            log("appVersionCode与fixAppVersion不一致，开始删除fixFile和清空fix.xml");
            if(fixFile.exists()){
                fixFile.delete();
            }
            preferences.edit().clear().commit(); //清空
        }
    }


    private void log(Object obj){
        if(DEBUG){
            Log.d("App", "---------"+obj+"---------");
        }
    }
    public static final boolean DEBUG = true;
}
